package com.mxz.common.file.service;

import com.mxz.common.file.config.MinioConfig;
import com.mxz.common.file.domain.CommFile;
import com.mxz.common.file.utils.FileUploadUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * Minio 文件存储
 *
 * @author mxz
 */
@Service
public class MinioFileServiceImpl implements CommFileService {
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;

    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return CommFile对象
     */
    @Override
    public CommFile uploadFile(MultipartFile file) {
        String fileName = FileUploadUtils.extractFilename(file);
        try {
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            client.putObject(args);
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败", e);
        }
        String url = minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
        return new CommFile(fileName, url);
    }

}
